define(window.backboneCommon.getViewDefine("campaign.info"), function ($,require,Collection,tpl,ViewStrategy,ViewCreative,ViewSpread) {
    var backboneView= Backbone.View.extend({
        events: {
            "click #chart_btnTotalGroup .btn": "changeChart",
            "shown.bs.tab #tab_group a[data-toggle='tab']": "changeTabs"
        },
        initialize: function () {
            this.modelAttach={};
            this.modelAttach.report=this.model.get("modelReport");
            this.listenTo(this.modelAttach.report, "bind:ReportCampaign", this.bindReport);
            this.listenTo(this.model, "bind:Info", this.bindCampaign);
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(id){
            if(id){
                this.elementModel={};
                this.elementModel.tab=$("#tab_group");
                this.elementModel.chart=$("#chart_campaign");
                this.elementModel.campaignTotal=$("#chart_campaign_total");
                this.elementModel.chartTab=$("#chart_btnTotalGroup");
                this.extObject={};
                this.pageData={campaignId:id,isReportShowIng:true,lastTab:"",isRefreshSpread:{strategy:true,creative:true}};
                this.pageData.initChartDefault=this.modelAttach.report.get("chartDefault");
                this.pageData.infoChartTabsQueue=$.ExtCommon.getJsonClone(this.modelAttach.report.get("chartQueue"));
                this.initViewAttach();
                this._initBodyMain();
            }else{
                $.ExtNotify.error("订单ID参数不存在");
                $.ExtAssist.goUrlHref("#campaign");
            }
        },
        initViewAttach:function () {
            var self=this;
            this.viewAttach={};
            this.viewAttach.strategy=new ViewStrategy({pElement:"#tab_strategy",campaignId:this.pageData.campaignId});
            this.viewAttach.creative=new ViewCreative({pElement:"#tab_creative",campaignId:this.pageData.campaignId});
            this.viewAttach.spread=new ViewSpread({pElement:"#tab_spread",campaignId:this.pageData.campaignId,
                jumpOutsideCallback:function (type,param) {self.selectTabs(type,param)},
                refreshCallback:function () {
                    self.pageData.isRefreshSpread.strategy=true;
                    self.pageData.isRefreshSpread.creative=true;
                }
            });
            var tabs=$.ExtCommon.getQueryStringByHash("tabs");
            var tabType=this._getTabsType(tabs);
            this.selectTabs(tabType);
        },
        _initBodyMain:function(){
            this.collection.getInfo(this.pageData.campaignId);
            this._initAssistCallback();
            this._initTimeRange();
            this._initReportData();
            this.extObject.campaignTotal=this.elementModel.campaignTotal.ExtFormValue({isRunBind:false});
        },
        _initAssistCallback:function(){
            var self=this;
            $.ExtAssist.winResize.callback("CampaignInfo",function(){
                if(self.pageData.chartReport){
                    self._bindChartData();
                    self.viewAttach.strategy.resizeChart()
                }
            });
        },
        bindCampaign:function(){
            var result=this.model.get("dataInfo");
            if(result.res.success){
                var name=result.res.data.name;
                $(".campaign-name").attr("title",name).text(name);
                $("#btn_campaignDetail").attr("href","#campaign/detail/"+this.pageData.campaignId);
                $.ExtAssist.urlParam.setUrl();
            }else{
                $.ExtNotify.error("订单详情数据获取失败："+result.res.msg);
            }
        },

        _initTimeRange:function () {
            var self=this;
            var initValue=this._initTimeVlaue();
            self.extObject.timeRange=$("#txt_campaign_timeRange").ExtDatePicker({type:"range",
                addQuick:{"本月": [$.ExtMoment.initMoment().startOf('month'), $.ExtMoment.initMoment()]},
                maxDate:$.ExtMoment.initMoment(),
                startValue:initValue.startTime,endValue:initValue.endTime,
                changeCallback: function () {
                    self._initReportData();
                    var timeValue=self._getTimeRangeValue();
                    self.viewAttach[self.pageData.lastTab].init(timeValue);
                }
            });
        },
        _initTimeVlaue:function () {
            return {startTime:$.ExtMoment.initFormat(),endTime:$.ExtMoment.initFormat()}
        },
        _getTimeRangeValue:function(){
            var arrTime =this.extObject.timeRange.getValue();
            return {startTime:arrTime[0],endTime:arrTime[1]}
        },

        _initReportData:function () {
            if (this.pageData.isReportShowIng) {
                this.pageData.isReportShowIng = false;
                var timeData =this._getTimeRangeValue();
                var tabsType = timeData.startTime === timeData.endTime ? "hour" : "day";
                var ajaxParam = {campaignId:this.pageData.campaignId};
                ajaxParam=$.ExtCommon.initMergeJson(ajaxParam,timeData);
                this.pageData.loadInfo={place: "box", boxId: "#chart_campaign", height: 235, type: "circle", dataListName: "list"};
                $.ExtAjax.initLoadStart(this.pageData.loadInfo);
                this.collection.getReport(tabsType,ajaxParam);
            }
        },
        _getReportOption: function (type) {
            var chartXAxisLen = type === "hour" ? -1 : 10;
            var charByDesc = type === "day";
            return {
                element:this.elementModel.chart, type: type,
                chart: {infoDefault:this.pageData.initChartDefault,
                    hoverTitle:"description",keyword: "description",
                    seriesType: "line", xAxisLen: chartXAxisLen, xOther: false, isDesc: charByDesc
                }
            };
        },
        bindReport:function () {
            var self=this;
            var result=self.modelAttach.report.get("dataReportCampaign");
            if(result.res.success){
                var type=result.req.type;
                var options = self._getReportOption(type);
                $.ExtReport.initBind(options, result.res.data.list, function (resJson) {
                    resJson.total=result.res.data.total;
                    self.pageData.chartReport =self._getMergeReportData(resJson);
                    self._bindChartData();
                    self._bindChartTotal();
                    self.pageData.isReportShowIng = true;
                    self.pageData.loadInfo.dataListLength=resJson.original.list.length;
                    $.ExtAjax.initLoadEnd(self.pageData.loadInfo)
                });
            }else{
                $.ExtNotify.error("报告数据获取失败："+result.res.msg)
            }
        },
        _getMergeReportData:function(resJson){
            var json=$.ExtCommon.getJsonClone(resJson);
            json.infoChartTabsQueue = this.pageData.infoChartTabsQueue;
            json.infoChartDefault = this.pageData.initChartDefault;
            return json;
        },
        _bindChartData:function(){
            if(this.pageData.chartReport.original.list.length>0){
                this.elementModel.chartTab.removeClass("display-hide").find(".btn").prop("disabled", false);
                this.elementModel.chart.show().next().hide();
                var chartOption=$.ExtReport.getChartOption(this.pageData.chartReport,{grid: {left: '5px', right: '10px', top: '25px', bottom: '5px'}});
                $.ExtReport.initECharts(this.elementModel.chart[0], chartOption);
            }else{
                this.elementModel.chart.hide();
                this.elementModel.chart.next().show();
                this.elementModel.chartTab.addClass("display-hide").find(".btn").prop("disabled", true);
            }
        },
        _bindChartTotal:function(){
            this.extObject.campaignTotal.setValues(this.pageData.chartReport.total);
            var elCounter=this.elementModel.campaignTotal.find(".counter");
            elCounter.ExtNumeric("refresh");
            $.each(elCounter, function (i, item) {
                var _this = $(item);
                var value = $.trim(_this.text().removesplit());
                if ($.ExtCommon.isCheckNum(value) && parseInt(value)>0) {
                    _this.ExtCountUp().start(0,value);
                }
            });
        },
        changeChart:function (e) {
            $.ExtNotify.destroy();
            var self=this;
            if(self.pageData.chartReport.original.list.length>0){
                var value=$(e.currentTarget).val();
                var arrValue=$.ExtReport.getChartTabsQueue(value,self.pageData.chartReport);
                if(arrValue.length>0){
                    self.elementModel.chartTab.find(".btn-default").toggleClass("btn-white btn-default");
                    $.each(arrValue,function(i,info){
                        self.elementModel.chartTab.find("button[value='"+info+"']").toggleClass("btn-white btn-default");
                    });
                    this._bindChartData();
                }else{
                    $.ExtNotify.error("必须保留一个!");
                }
            }
        },

        _getTabsType:function(tabs){
            var tabType="strategy";
            if(!$.ExtCommon.isCheckEmpty(tabs)){
                switch(tabs){
                    case "0":
                        tabType="spread";
                        break;
                    case "1":
                        tabType="strategy";
                        break;
                    case "2":
                        tabType="creative";
                        break;
                }
            }
            return tabType;
        },
        selectTabs:function (type,extParam) {
            var el=this.elementModel.tab.find('[data-tab-page-type="'+type+'"]');
            el.parent().addClass("active").siblings().removeClass("active");

            $("#tab_"+type).addClass("active").siblings().removeClass("active");
            this._operateTabs(el,extParam);
        },
        changeTabs:function (e) {
            this._operateTabs($(e.currentTarget))
        },
        _operateTabs:function (element,param) {
            var newParam = $.ExtCommon.initMergeJson({}, param || {});
            var type = element.data("tabPageType");
            var lastTimeValue = $.ExtCommon.isCheckEmpty(this.pageData.lastTab)
                ? this._initTimeVlaue()
                : this.viewAttach[this.pageData.lastTab].getTimeValue();
            newParam = $.ExtCommon.initMergeJson(newParam, lastTimeValue);
            var text = element.find("span").text();
            $(".page-operate-title,title").text(text);
            this.pageData.lastTab = type;
            newParam.isRefreshSpread=this.pageData.isRefreshSpread[type];
            this.pageData.isRefreshSpread[type]=false;
            this.viewAttach[type].init(newParam);
        }
    });
    var viewModel=function(){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({el: "#container_body",collection:this.collection,model:this.model});
    };
    viewModel.prototype={
        initView:function (param) {
            var id=param?param[0]:null;
            this.view.initMain(id);
        }
    };
    return viewModel;
});